package com.ywjh.inter.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Timestamp;
import java.util.Calendar;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.ywjh.inter.entity.BindInsulinEntity;
import com.ywjh.inter.entity.DataInsulinEntity;
import com.ywjh.inter.entity.EquInsulinStatEntity;
import com.ywjh.inter.service.InsulinService;
import com.ywjh.inter.utils.StrUtil;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

/**
 * 胰岛素相关的接口
 * 
 * @author yao
 *
 */
public class Insulin extends HttpServlet {
	
	

	/**
	 * 
	 */
	private static final long serialVersionUID = -8554870001597437909L;

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		resp.setCharacterEncoding("UTF-8");
		resp.setContentType("text/html; charset=utf-8");

		JSONObject postData = StrUtil.getPostJSON(req);
		String act = postData.getString("act");
		JSONObject data = postData.getJSONObject("data");
		int r = 0;
		String e = "";
		JSONObject json = new JSONObject();
		switch (act) {
		case "bind":// 绑定胰岛素设备
			String equ_name = data.getString("equ_name");
			String equ_mac = data.getString("equ_mac");
			int doc_id = StrUtil.getInt(data.getString("doc_id"), 0);
			Timestamp time = new Timestamp(System.currentTimeMillis());
			int patient_id = StrUtil.getInt(data.getString("patient_id"), 0);
			BindInsulinEntity entity = InsulinService.getInstance().findInsulin(equ_name, equ_mac);
			if (entity == null) {
				entity = new BindInsulinEntity();
				entity.setAdd_time(time);
				entity.setDoc_id(doc_id);
				entity.setEqu_mac(equ_mac);
				entity.setEqu_name(equ_name);
				entity.setPatient_id(patient_id);
				entity.setStatus(1);
				boolean b = InsulinService.getInstance().bindInsulin(entity);
				if (b) {
					r = 1;
				} else {
					e = "数据库错误";
				}
			} else {
				e = "设备已经绑定";
			}
			break;
		case "unbind":// 解除绑定胰岛素泵
			doc_id = StrUtil.getInt(data.getString("doc_id"), 0);
			time = new Timestamp(System.currentTimeMillis());
			patient_id = StrUtil.getInt(data.getString("patient_id"), 0);
			entity = InsulinService.getInstance().findInsulinByPatientId(patient_id);
			if (entity != null) {
				entity.setAdd_time(time);
				entity.setDoc_id(doc_id);
				entity.setPatient_id(patient_id);
				entity.setStatus(0);
				boolean b = InsulinService.getInstance().unbindInsulin(entity);
				if (b) {
					r = 1;
				} else {
					e = "数据库错误";
				}
			} else {
				e = "设备未绑定";
			}
			break;
		case "check_bind":// 批量检测设备是否被绑定
			String mac_array = data.getString("mac_array");
			System.out.println("check_bind req:"+mac_array);
			String[] macs = mac_array.split(",");
			Map<String, Integer> dataMap = InsulinService.getInstance().checkInsulinBind(macs);
			JSONArray array = new JSONArray();
			for (String mac : dataMap.keySet()) {
				JSONObject d = new JSONObject();
				d.put("mac", mac);
				d.put("is_bind", dataMap.get(mac));
				array.add(d);
			}
			r = 1;
			System.out.println("check_bind resp:"+array.toString());
			json.put("d", array);
			break;
		case "rsync_info":// 同步设备状态数据
			String equ_no = data.getString("equ_no");
			Timestamp equ_time = StrUtil.getTimestampHHMISS(data.getString("equ_time"));
			float dosageLess = StrUtil.getFloat(data.getString("dosage_less"), 0.0f);
			float powerLess = StrUtil.getFloat(data.getString("power_less"), 0.0f);
			EquInsulinStatEntity statEntity = new EquInsulinStatEntity();
			statEntity.setAdd_time(new Timestamp(System.currentTimeMillis()));
			statEntity.setDosage_less(dosageLess);
			statEntity.setEqu_no(equ_no);
			statEntity.setEqu_time(equ_time);
			statEntity.setPower_less(powerLess);
			boolean b = InsulinService.getInstance().rsynInsulinEquStat(statEntity);
			if (b) {
				r = 1;
			}
			break;
		case "get_info":// 查询上一次胰岛素设备
			equ_no = data.getString("equ_no");
			statEntity = InsulinService.getInstance().findEquInsulinByEquNo(equ_no);
			if (statEntity == null) {
				r = -1;
				e = "胰岛素设备:" + equ_no + " 没有找到";
			} else {
				JSONObject dataJson = new JSONObject();
				dataJson.put("equ_no", statEntity.getEqu_no());
				dataJson.put("power_less", statEntity.getPower_less());
				dataJson.put("dosage_less", statEntity.getDosage_less());
				dataJson.put("equ_time", StrUtil.getYYYYMMDDHHMI(statEntity.getEqu_time()));
				dataJson.put("add_time", StrUtil.getYYYYMMDDHHMI(statEntity.getAdd_time()));
				json.put("d", dataJson);
				r = 1;
			}
			break;
		case "rsync_data":// 同步数据
			equ_name = data.getString("equ_name");
			equ_mac = data.getString("equ_mac");
			doc_id = StrUtil.getInt(data.getString("doc_id"), 0);
			String[] data_array = data.getString("data").split(",");
			int type = StrUtil.getInt(data.getString("type"), 0);
			String[] memo = data.getString("memo").split(",");
			String[] check_time = data.getString("check_time").split(",");
			System.out.println("type=" + type + "===" + equ_mac + " " + equ_name + " " + data.getString("data") + " "
					+ data.getString("check_time"));
			List<DataInsulinEntity> dataList = new LinkedList<>();
			patient_id = 0;
			for (int i = 0; i < memo.length; i++) {

				if (type == 2) {
					// 如果是基础率时间是没有HH:MI:SS,否则当天绑定的基础率是提交不上的。
					patient_id = InsulinService.getInstance().getBindPatientByInsulinEqu(equ_name, equ_mac);
				} else {
					patient_id = InsulinService.getInstance().getBindPatientByInsulinEqu(equ_name, equ_mac,
							StrUtil.getTimestampHHMISS(check_time[i]));
				}
				if (patient_id > 0) {
					DataInsulinEntity dataInsulinEntity = new DataInsulinEntity();
					dataInsulinEntity.setAdd_time(new Timestamp(System.currentTimeMillis()));
					dataInsulinEntity.setDoc_id(doc_id);
					dataInsulinEntity.setPatient_id(patient_id);
					dataInsulinEntity.setStatus(1);
					dataInsulinEntity.setData(Float.valueOf(data_array[i]));
					dataInsulinEntity.setType(type);
					dataInsulinEntity.setMemo(memo[i]);
					dataInsulinEntity.setCheck_time(StrUtil.getTimestampHHMISS(check_time[i]));
					dataList.add(dataInsulinEntity);
				} else {
					System.out.println("患者未绑定：" + check_time[i]);
				}
			}
			b = false;
			if (type == 2) {// 基础率先清空在插入
				b = InsulinService.getInstance().rsynInsulin(dataList, patient_id, type);
			} else {
				b = InsulinService.getInstance().rsynInsulin(dataList);
			}
			if (b) {
				r = 1;
			} else {
				e = "数据库错误";
			}
			break;
		case "common_data":// 获得基础率的通用设置
			String name = data.getString("name");
			String max_value = data.getString("max_value");
			String key = "insulin_" + name + "_" + max_value;
			String v = InsulinService.getInstance().getInsulinCommData(key);
			json.put("d", v);
			r = 1;
			break;
		case "get_data":// 获得用户的胰岛素数据
			String start_time = data.getString("start_time");
			String end_time = data.getString("end_time");
			Calendar cal = Calendar.getInstance();
			cal.setTimeInMillis(StrUtil.getTimestamp(end_time).getTime());
			cal.add(Calendar.DATE, 1);
			end_time = StrUtil.getYYYYMMDD(new Timestamp(cal.getTimeInMillis()));
			patient_id = StrUtil.getInt(data.getString("patient_id"), 0);
			type = StrUtil.getInt(data.getString("type"), 0);
			List<DataInsulinEntity> list = InsulinService.getInstance().queryInsulinData(start_time, end_time,
					patient_id, type);
			array = new JSONArray();
			for (DataInsulinEntity dataInsulinEntity : list) {
				JSONObject o = new JSONObject();
				o.put("time", StrUtil.getYYYYMMDDHHMI(dataInsulinEntity.getCheck_time()));
				o.put("data", dataInsulinEntity.getData());
				o.put("type", dataInsulinEntity.getType());
				o.put("memo", dataInsulinEntity.getMemo());
				array.add(o);
			}
			r = 1;
			json.put("d", array);
			break;

		}
		json.put("r", r);
		json.put("e", e);
		PrintWriter pw = resp.getWriter();
		pw.write(json.toString());
		pw.flush();
		pw.close();
	}
}
